//
//  MusicController.m
//  planning
//
//  Created by mac on 2019/7/30.
//  Copyright © 2019 mac. All rights reserved.
//

#import "ZZMusicsController.h"

#import "ZZMusic.h"

#import "ZZMusicCell.h"

#import "ZZAudioTool.h"

#import "ZZPlayerToolBar.h"

#import "NSString+ZZ.h"

#import "AppDelegate.h"

#import <AVFoundation/AVFoundation.h>

@interface  ZZMusicsController ()<UITableViewDelegate,UITableViewDataSource,AVAudioPlayerDelegate,ZZPlayerToolBarDelegate>

@property (nonatomic, strong) NSMutableArray *musics;

@property (nonatomic, strong) AVAudioPlayer *currentPlayingAudioPlayer;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, weak) UIImageView *imgView;

@property (nonatomic, weak) ZZPlayerToolBar *playToolBar;

/**
 
 *  当前播放的索引
 
 */

@property (nonatomic, assign) NSInteger musicIndex;

@end

@implementation ZZMusicsController

#pragma mark - 懒加载

- (NSMutableArray *)musics
{
    if (!_musics) {
        _musics = [NSMutableArray array];
    }
    return  _musics;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self initData];
    
    //设置导航栏背景图片为一个空的image，这样就透明了
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    //去掉透明后导航栏下边的黑边
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar  setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}


- (void)initData {
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSArray *fileArrey = [fileManager contentsOfDirectoryAtPath:kMusicPath error:nil];
    [self.musics removeAllObjects];
    for (NSString *fileName in fileArrey) {
        NSString *urlString = [kMusicPath stringByAppendingPathComponent:fileName];
        ZZMusic *music = [[ZZMusic alloc] init];
        music.name = fileName;
        music.filename = urlString;
        music.singer = @"作者";
        music.singerIcon = @"音乐";
        music.icon = @"音乐";
        [self.musics addObject:music];
    }
    [_tableView reloadData];
}

- (void)viewDidLoad {
    
    [super  viewDidLoad];
    
    // 1.初始化playerToolBar
    [self  setUpPlayerToolBar];
    
    // 2.随机播放
//    [self  selectIndexPathWithRow:self.musicIndex];
    
    // 3.接收远程事件
    [self  setUpRemovteEvent];
    
}

#pragma mark - setUp 初始化

- (void)setUpRemovteEvent

{
    
    ((AppDelegate *)[UIApplication sharedApplication].delegate).removteBlock = ^(UIEvent *event) {
        
        switch (event.subtype) {
                
            case  UIEventSubtypeRemoteControlNextTrack:
                
                [self playNextMusic];
                
                break;
                
            case  UIEventSubtypeRemoteControlPreviousTrack:
                
                [self playPreviousMusic];
                
                break;
                
            case  UIEventSubtypeRemoteControlPause:
                
                [self pauseCurrentMusic];
                
                break;
                
            case  UIEventSubtypeRemoteControlPlay:
                
                [self playCurrentMusic];
                
                break;
            default:
                break;
        }
        
    };
    
}

- (void)setUpPlayerToolBar
{
    ZZPlayerToolBar *playToolBar = [ZZPlayerToolBar  playerToolBar];
    
    playToolBar.frame = CGRectMake(0, self.view.frame.size.height - 240, self.view.frame.size.width, 100);
    
    playToolBar.delegate = self;
    
    [self.view addSubview:playToolBar];
    
    self.playToolBar = playToolBar;
    
}


#pragma mark - ZZPlayerToolBarDelegate

- (void)playerToolBar:(ZZPlayerToolBar *)playerToolBar didClickBtnWithType:(ZZPlayerToolBarButtonType)type

{
    
    switch (type) {
            
        case  ZZPlayerToolBarPreviousButtonType:
            
            [self  playPreviousMusic];
            
            break;
            
        case  ZZPlayerToolBarNextButtonType:
            
            [self playNextMusic];
            
            break;
            
        case  ZZPlayerToolBarPlayButtonType:
            
            [self playCurrentMusic];
            
            break;
            
        case  ZZPlayerToolBarPauseButtonType:
            
            [self  pauseCurrentMusic];
            
            break;
            
        case  ZZPlayerToolBarTypeButtonType:
            
            [self playStyleMusic];
            
            break;
            
        default:
            
            break;
            
    }
    
}

/**
 
 *  播放上一首
 
 */

- (void)playPreviousMusic

{
    
    if (self.musicIndex == 0) { // 第一首则回到最后一首
        
        self.musicIndex = self.musics.count - 1;
        
    } else {
        
        self.musicIndex--;
        
    }
    
    [self  selectIndexPathWithRow:self.musicIndex];
    
}

/**
 
 *  播放下一首
 
 */

- (void)playNextMusic

{
    
    if (self.musicIndex == self.musics.count - 1) { // 最后一首
        
        self.musicIndex = 0;
        
    } else {
        
        self.musicIndex++;
        
    }
    
    [self  selectIndexPathWithRow:self.musicIndex];
    
}

/**
 
 *  播放
 
 */

- (void)playCurrentMusic

{
    
    [[ZZAudioTool  shareInstance] play];
    
}

/**
 
 *  暂停
 
 */

- (void)pauseCurrentMusic

{
    
    [[ZZAudioTool  shareInstance] pause];
    
}

/**
 
 *  更换播放模式
 
 */

- (void)playStyleMusic

{
    
}

- (void)selectIndexPathWithRow:(NSInteger)row

{
    // 0.取得当前选中
    NSIndexPath *selectedPath = [self.tableView indexPathForSelectedRow];
    
    // 1.主动选中下一行
    NSIndexPath *currentPath = [NSIndexPath indexPathForRow:row inSection:selectedPath.section];
    
    [self.tableView  selectRowAtIndexPath:currentPath animated:YES  scrollPosition:UITableViewScrollPositionTop];
    
    [self  tableView:self.tableView  didSelectRowAtIndexPath:currentPath];
    
    // 2.播放音乐
    [self  playMusic];
    
}

/**
 
 *  播放音乐
 
 */

- (void)playMusic

{
    
    // 0.取出播放的歌曲
    
    ZZMusic *music = self.musics[self.musicIndex];
    
    music.playing = YES;
    
    // 1.初始化播放器
    
    [[ZZAudioTool  shareInstance] prepareToPlayWithMusic:music];
    
    // 2.设置代理
    
    [ZZAudioTool  shareInstance].player.delegate = self;
    
    // 3.更改播放工具条数据
    
    self.playToolBar.music = self.musics[self.musicIndex];
    
    // 4.播放
    
    [[ZZAudioTool  shareInstance] play];
    
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{
    
    return  self.musics.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    // 1.创建cell
    
    ZZMusicCell *cell = [ZZMusicCell cellWithTableView:tableView];
    
    // 2.设置cell的数据
    
    cell.music = self.musics[indexPath.row];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    return 70;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    // 0.取出要播放的音乐
    
    ZZMusic *music = self.musics[indexPath.row];
    
    if (music.playing == YES) return;
    
    music.playing = YES;
    
    // 1.取得索引值
    
    self.musicIndex = indexPath.row;
    
    // 2.播放音乐
    
    [self  playMusic];
    
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    // 0.停止音乐直接释放
    
    ZZMusic *music = self.musics[indexPath.row];
    
    music.playing = NO;
    
    [ZZAudioTool  stopMusic:music.filename];
    
}

#pragma mark - AVAudioPlayerDelegate

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag

{
    
    if (!flag == YES) return;
    
    [self  playNextMusic];
    
}

@end
